import { Empty, Message, Progress, Table } from '@arco-design/web-react';
import { useEffect, useRef, useState } from 'react';
import { apiGetTaskMqCardDetail } from '../../../api';
import { TaskMqCard } from '../../../types';
import { apiGetTaskMqCardDetailList } from '../../../api';
import { TaskMqCardDetail } from '../../../types';
import { TaskMqImport } from '../../../types';
import {getDict} from '../../../utils/utils';
import DetailModal from '../../../components/detailModal';
import { dictTag } from '../../../utils/utils';

interface Props {
  id: string;
  onCancel: () => void;
}

// 重试次数 如果进度没变化 够次数之后不再请求
const retryCount = 10;

const COMMON_TASK_STATUS = 'common_task_status';
export default function CardDetailProgressDialog({ id, onCancel }: Props) {
  const [detail, setDetail] = useState<TaskMqCard>();
  const [list, setList] = useState<TaskMqCardDetail[]>([]);
  const [fetching, setFetching] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState('');
  // 记录当前已重试次数 和前一次的进度
  const retryRef = useRef<{ retryCount: number; percentage: number }>({ retryCount: 0, percentage: 0 });
  const [dictDatas, setDictDatas] = useState<Record<string, any>>({});
  const timeRef = useRef<NodeJS.Timer>();
  const dataRef = useRef<TaskMqImport[]>();
  const detailRef = useRef<TaskMqImport>();
 
  useEffect(() => {
    startTimer();
    async function fetchDictData() {
      const data = await getDict(COMMON_TASK_STATUS);
      setDictDatas(data);
    }

    fetchDictData();
    return () => {
      if (timeRef.current) {
        clearInterval(timeRef.current);
        timeRef.current = undefined;
      }
    };
  }, []); //eslint-disable-line

  function startTimer() {
    if (timeRef.current) {
      clearInterval(timeRef.current);
    }
    loadProgress();
    timeRef.current = setInterval(() => {
      if (dataRef.current && !dataRef.current.length) {
        clearInterval(timeRef.current);
        timeRef.current = undefined;
      }
      loadProgress();
    }, 2000);
  }

  async function loadProgress() {
    let ids = id.split(',');
    if (retryRef.current.retryCount < retryCount) {
      // 如果在重试次数内
      if ((detailRef.current?.percentage ?? 0) !== retryRef.current.percentage) {
        // 如果详情里的进度不等于记录的进度就重置重试次数 并记录最近一次请求的进度
        retryRef.current.retryCount = 0;
        retryRef.current.percentage = detailRef.current?.percentage ?? 0;
      } else {
        /// 如果进度没有变 则重试次数+1
        retryRef.current.retryCount++;
      }
      if ((detailRef.current?.percentage ?? 0) < 100) {
        try {
          let res = await apiGetTaskMqCardDetail(ids[0]);
          let data = res.data;
          if (data.code === 200) {
            setDetail(data.data);
            detailRef.current = data.data;
          } else {
            Message.warning(data.msg ?? '加载失败');
          }
        } catch (e: any) {
          Message.error(e.message ?? '加载失败');
        }
      }
      let _list: TaskMqCardDetail[] = [];
      let code = 500;
      try {
        for (let i of ids) {
          let res = await apiGetTaskMqCardDetailList(1, 1000, { taskGroupId: i });
          let data = res?.data;
          if (data.code !== 200) {
            setError(data.msg ?? '加载失败');
          }
          code = data.code;
          _list = _list.concat(data.rows ?? []);
        }
        if (!loaded) {
          setLoaded(true);
        }
        if (fetching) {
          setFetching(false);
        }
        if (code === 200) {
          setList(_list);
        } else {
          setList([]);
        }
      } catch (e: any) {
        setError(e.messag ?? '加载失败');
      } finally {
        // 检查是否还有等待中的，如果没有等待中的 则停止定时器
        let _waitingList = _list.filter((i) => i.status === 'waiting');
        if (!_waitingList.length) {
          clearInterval(timeRef.current);
          timeRef.current = undefined;
        }
      }
    } else {
      // 如果超过重试次数 则直接结束
      clearInterval(timeRef.current);
      timeRef.current = undefined;
    }
  }

  let dataSource = (list || []).map((item) => Object.assign({}, item, { key: item.id }));

  // 定义类型表格内的列
  const dataColumns = [
    {
      title: '任务名',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '充值卡号',
      dataIndex: 'businessNo',
      key: 'businessNo',
      width: 200,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (v: string) => dictTag(v, dictDatas[COMMON_TASK_STATUS]),
    },
    {
      title: '状态提示',
      dataIndex: 'statusRemark',
      key: 'statusRemark',
      width: 200,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 180,
    },
  ];
  return (
    <DetailModal show title="卡操作" className="bw-80" cancelBtnShow={false} onConfirm={onCancel} onCancel={onCancel} >
      <Progress className="mb-20" strokeWidth={10} percent={detail?.percentage ?? 0} />
      <Table
        className="bw-100"
        data={dataSource}
        columns={dataColumns}
        pagination={false}
        loading={!list || (fetching && !loaded)}
        noDataElement={<Empty description={error ?? '暂无数据'} />}
      />
    </DetailModal>
  );
}
